<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/4/24
 * Time: 11:10 AM
 */

namespace App\Services;

use App\Models\Admin;
use App\Models\WechatAccount;
use App\Models\WechatAccountCategory;
use App\Models\WechatAccountChat;
use App\Models\WechatAccountCustomer;
use App\Models\WechatCategory;
use App\Models\WechatCorp;
use App\Models\WechatUserAdmin;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

class UserService
{

    /**
     * 获取部门成员列表
     *
     * @param $params
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getUserList($params)
    {
        $corpId = $params['corp_id'] ?? '';
        $depId  = $params['department_id'] ?? '';

        $query = WechatAccount::query()->where('corp_id', $corpId);
        if ($depId) {
            $query->where('department_id', $depId);
        }
        $list = $query->get();
        foreach ($list as &$item) {
            $assignAdminIds           = WechatUserAdmin::query()->where('user_id', $item->user_id)->pluck('admin_id');
            $assignCategoryIds        = WechatAccountCategory::query()->where('user_id', $item->user_id)->pluck('category_id');
            $item->is_assign_admin    = $assignAdminIds->isNotEmpty() ? true : false;
            $item->assign_admin       = $assignAdminIds->isNotEmpty() ?
                Admin::query()->whereIn('id', $assignAdminIds)->pluck('name')->implode('，') : '';
            $item->is_assign_category = $assignCategoryIds->isNotEmpty() ? true : false;
            $item->assign_category    = $assignCategoryIds->isNotEmpty() ?
                WechatCategory::query()->whereIn('id', $assignCategoryIds)->pluck('category_name')->implode('，') : '';
        }

        return $list;
    }


    public function getAll()
    {
        return WechatAccount::query()->select('user_id', 'user_name')->get();
    }


    /**
     * 创建成员
     *
     * @param $params
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function createUser($params)
    {
        $corpId     = $params['corp_id'] ?? '';
        $userid     = $params['userid'] ?? '';
        $name       = $params['name'] ?? '';
        $mobile     = $params['mobile'] ?? '';
        $department = $params['department'] ?? 0;
        $position   = $params['position'] ?? '';
        $gender     = $params['gender'] ?? 1;

        $client   = new Client();
        $service  = new KfAccountService();
        $token    = $service->getReplaceAccessToken($corpId);
        $body     = [
            'headers'            => $service->headers,
            RequestOptions::JSON => [
                'userid'     => $userid,
                'name'       => $name,
                'mobile'     => $mobile,
                'department' => $department,
                'position'   => $position,
                'gender'     => $gender,
            ]
        ];
        $response = $client->request('POST', sprintf($service->api['create_user'], $token), $body);
        if ($response->getStatusCode() != 200) {

            return false;
        }

        $contents = $response->getBody()->getContents();
        $data     = json_decode($contents, true);
        if ($data['errcode'] == 0) {
            $account                = new WechatAccount();
            $account->corp_id       = $corpId;
            $account->department_id = $department;
            $account->user_id       = $userid;
            $account->user_name     = $name;
            $account->save();

            return true;
        }

        return false;
    }


    /**
     * 删除成员
     *
     * @param $params
     * @return bool
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function delUser($params)
    {
        $corpId = $params['corp_id'] ?? '';
        $id     = $params['id'] ?? 0;

        $client   = new Client();
        $service  = new KfAccountService();
        $token    = $service->getReplaceAccessToken($corpId);
        $response = $client->request('GET', sprintf($service->api['del_user'], $token, $id));
        if ($response->getStatusCode() != 200) {

            return false;
        }
        $contents = $response->getBody()->getContents();
        $data     = json_decode($contents, true);
        if ($data['errcode'] == 0) {
            $account = WechatAccount::query()->where('corp_id', $corpId)->where('user_id', $id)->first();
            if ($account) {
                $account->delete();
            }

            return true;
        }

        return false;
    }


    /**
     * 分配用户分类
     *
     * @param $params
     * @return bool
     */
    public function assignUserCategory($params)
    {
        $corpId     = $params['corp_id'] ?? '';
        $userId     = $params['user_id'] ?? '';
        $categoryId = $params['category_id'] ?? 0;

        if (!$userId || !$categoryId) {

            return false;
        }

        // 如果已经分配过则删除分配
        if ($userCategory = WechatAccountCategory::query()->where(['user_id' => $userId, 'category_id' => $categoryId])->first()) {
            $userCategory->delete();

            return true;
        } else {
            $userCategory          = WechatAccountCategory::query()->firstOrNew(['user_id' => $userId, 'category_id' => $categoryId]);
            $userCategory->corp_id = $corpId;

            return $userCategory->save();
        }
    }


    /**
     * 分配用户运营
     *
     * @param $params
     * @return bool
     */
    public function assignUserAdmin($params)
    {
        $corpId  = $params['corp_id'] ?? '';
        $userId  = $params['user_id'] ?? '';
        $adminId = $params['admin_id'] ?? 0;

        if (!$userId || !$adminId) {

            return false;
        }
        // 如果已经分配过则删除分配
        if ($userAdmin = WechatUserAdmin::query()->where(['user_id' => $userId, 'admin_id' => $adminId])->first()) {
            $userAdmin->delete();

            return true;
        } else {
            $userAdmin          = WechatUserAdmin::query()->firstOrNew(['user_id' => $userId, 'admin_id' => $adminId]);
            $userAdmin->corp_id = $corpId;

            return $userAdmin->save();
        }
    }


    /**
     * 获取账号池
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getUserPool()
    {
        $list = WechatAccount::query()
            ->with([
                'department'            => function ($query) {
                    $query->select('department_id', 'department_name');
                },
                'userCategory'          => function ($query) {
                    $query->select('user_id', 'category_id');
                },
                'userCategory.category' => function ($query) {
                    $query->select('id', 'category_name');
                }
            ])
            ->whereIn('user_id', UtilityService::getPermissionUserIds())
            ->get();

        foreach ($list as &$item) {
            $item->category       = optional($item->userCategory)->category ?? [];
            $item->corp_name      = WechatCorp::query()->where('corp_id', $item->corp_id)->value('corp_name');
            $item->chat_count     = WechatAccountChat::query()->where('user_id', $item->user_id)->count();
            $item->customer_count = WechatAccountCustomer::query()->where('account_id', $item->user_id)->count();
            unset($item->userCategory);
        }

        return $list;
    }
}
